package com.shh.shojbackendjudgeservice.judge;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import com.shh.shojbackendcommon.annotation.LogExecutionTime;
import com.shh.shojbackendjudgeservice.judge.codesandbox.CodeSandbox;
import com.shh.shojbackendjudgeservice.utils.ProcessUtils;
import com.shh.shojbackendmodel.model.codesandbox.ExecuteCodeRequest;
import com.shh.shojbackendmodel.model.codesandbox.ExecuteCodeResponse;
import com.shh.shojbackendmodel.model.codesandbox.ExecuteMessage;
import com.shh.shojbackendmodel.model.codesandbox.JudgeInfo;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 代码沙箱统一模板
 */
@Service
public class JavaCodeSandboxTemplate implements CodeSandbox {
    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";



//    public static void main(String[] args) {
//       JavaCodeSandboxTemplate javaCodeSandboxTemplate = new JavaCodeSandboxTemplate();
//       ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
//       executeCodeRequest.setInputList(Arrays.asList("1 2","2 2","3 6"));
//       String code = ResourceUtil.readStr("D:\\code\\back\\OjProject\\shoj_backend_mircoservice_master\\src\\main\\resources\\tmpCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
//       executeCodeRequest.setCode(code);
//       executeCodeRequest.setLanguage("java");
//       ExecuteCodeResponse executeCodeResponse = javaCodeSandboxTemplate.executeCode(executeCodeRequest);
//       System.out.println(executeCodeResponse);
//   }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        //一、存放用户代码
        File userCodeFile = setUserCode(executeCodeRequest);
        System.out.println("用户代码存放路径：" + userCodeFile.getAbsolutePath());

        //二`编译代码 得到class文件
        try {
            ExecuteMessage executeMessage = CompileCode(userCodeFile);
            System.out.println(executeMessage.getMessage());
        } catch (IOException e) {
            return getErrorResponse(e);
        }

        //三`运行代码 iter快捷键
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        try {
            executeMessageList = RunCode(inputList,userCodeFile);
        }catch (Exception e){
            return getErrorResponse(e);
        }

        //四 输出并整理结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse = getResponse(executeMessageList);

        //删除文件
        delFile(userCodeFile);

        return executeCodeResponse;
    }

    /**
     * 一、存储用户代码
     * @param executeCodeRequest
     * @return
     */
    public File setUserCode(ExecuteCodeRequest executeCodeRequest){
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();


        //获取根目录
        String userDir = System.getProperty("user.dir");

        String globalCodePathName = userDir + File.separator  + GLOBAL_CODE_DIR_NAME;
        //判断全局用户代码是否存在 如果不存在创建
        if(!FileUtil.exist(globalCodePathName)){
            FileUtil.mkdir(globalCodePathName);
        }

        //把用户代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;

        File userCodeFile =  FileUtil.writeString(code,userCodePath, StandardCharsets.UTF_8);
        return userCodeFile;
    }



    /**
     * 二、编译代码
     * @param userCodeFile
     * @return
     * @throws IOException
     */
    public ExecuteMessage CompileCode(File userCodeFile) throws IOException {
        //获取code目录的绝对路径Process compileProcess
        String CompileCommand =  String.format("javac -encoding UTF-8 %s",userCodeFile.getAbsolutePath());
        //执行命令代码 响应结果是一个进程
        Process compileProcess = Runtime.getRuntime().exec(CompileCommand);
        ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess,"编译");
        return executeMessage;
    }

    /**
     * 三、运行代码
     * @param inputList
     * @param userCodeFile
     * @return
     * @throws IOException
     */
    @LogExecutionTime
    public List<ExecuteMessage> RunCode(List<String> inputList,File userCodeFile) throws IOException {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs: inputList) {
            //用-Dfile.encoding=UTF-8  可以解决运行结果乱码问题
            String runCMD = String.format("java -Dfile.encoding=UTF-8 -cp %s Main %s",userCodeParentPath,inputArgs);
            Process compileProcess = Runtime.getRuntime().exec(runCMD);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess,"运行");
            executeMessageList.add(executeMessage);
        }
        return executeMessageList;
    }

    /**
     * 四、获取输出结果
     * @param executeMessageList
     * @return
     */
    public ExecuteCodeResponse getResponse(List<ExecuteMessage> executeMessageList){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        // 取用时最大值，便于判断是否超时
        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                // 用户提交的代码执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        // 正常运行完成
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        // 要借助第三方库来获取内存占用，非常麻烦，此处不做实现
//        judgeInfo.setMemory();

        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }

    public Boolean delFile(File userCodeFile){
        boolean del = false;
        if (userCodeFile.getParentFile() != null) {
            del = FileUtil.del(userCodeFile.getParentFile().getAbsolutePath());
        }
        return del;
    }

    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }

}
